<template>
  <div class="account-box">
    <div class="name" style="width: 640px; height: 70px; text-align: center; font-size: 24px; line-height: 70px; margin-bottom: 10px">欢迎注册优乐购物</div>
    <Form ref="formTarget" class="form" :validation-schema="schema" v-slot="{errors}" autocomplete="off">
      <div class="form-item">
        <div class="input">
          <i class="iconfont icon-zhanghao" />
          <Field v-model="form.account" name="account" :class="{error:errors.account}" type="text" placeholder="请设置账户名" />
        </div>
        <div class="error" v-if="errors.account">
          <i class="iconfont icon-warning" />
          {{errors.account}}
        </div>
      </div>
      <div class="form-item">
          <div class="input">
            <i class="iconfont icon-phone" />
            <Field name="mobile" :class="{error:errors.mobile}" v-model="form.mobile" type="text" placeholder="请输入手机号" />
          </div>
          <div class="error" v-if="errors.mobile">
            <i class="iconfont icon-warning" />
            {{errors.mobile}}
          </div>
      </div>
      <div class="form-item">
        <div class="input">
          <i class="iconfont icon-code" />
          <Field name="code" v-model="form.code" :class="{error:errors.code}" type="text" placeholder="请输入验证码" />
          <span @click="send()" class="code">
            {{time === 0 ? '发送验证码' : `${time}秒后发送`}}
          </span>
        </div>
        <div class="error" v-if="errors.code">
          <i class="iconfont icon-warning" />
          {{errors.code}}
        </div>
      </div>
      <div class="form-item">
        <div class="input">
          <i class="iconfont icon-suo" />
          <Field name="password" v-model="form.password" :class="{error:errors.password}" type="password" placeholder="请设置6至20位字母、数字和符号组合的复杂密码" autocomplete="off"/>
        </div>
        <div class="error" v-if="errors.password">
          <i class="iconfont icon-warning" />
          {{errors.password}}
        </div>
      </div>
      <div class="form-item">
        <div class="input">
          <i class="iconfont icon-safe" />
          <Field name="repassword" v-model="form.repassword" :class="{error:errors.repassword}" type="password" placeholder="请再次输入您设置的密码" autocomplete="off"/>
        </div>
        <div class="error" v-if="errors.repassword">
          <i class="iconfont icon-warning" />
          {{errors.repassword}}
        </div>
      </div>
      <div class="form-item">
        <div class="agree">
          <!-- <XtxCheckbox v-model="form.isAgree" /> -->
          <Field name="isAgree" as="XtxCheckbox" v-model="form.isAgree" />
          <span>用户勾选即代表同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree">
          <i class="iconfont icon-warning" />
            {{errors.isAgree}}
        </div>
      </div>
      <a @click="submit()" href="javascript:;" class="btn">注册</a>
    </Form>
    <div class="action">
      <div class="url">
        有账号，<RouterLink class="green" to="/login">直接登录</RouterLink>
      </div>
    </div>
  </div>
</template>

<script>
import { onUnmounted, reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import { getRegMobileCode, userAccountRegist } from '@/api/user'
import schema from '@/utils/vee-validate-schema'
// import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/library/message'
// import QC from 'qc'
export default {
  name: 'RegistForm',
  components: {
    Form,
    Field
  },
  setup () {
    // 表单信息对象
    const form = reactive({
      isAgree: true,
      account: null,
      password: null,
      repassword: null,
      mobile: null,
      code: null,
      type: '' // 注册端类型，默认空
    })
    // 定义校验规则对象
    const mySchema = {
      account: schema.account,
      password: schema.password,
      repassword: schema.repassword,
      mobile: schema.mobile,
      code: schema.code,
      isAgree: schema.isAgree
    }
    // 需要在点击注册的时候对整体表单进行校验
    // const store = useStore()
    const formTarget = ref(null)
    const router = useRouter()
    const route = useRoute()
    const submit = async () => {
      // Form组件提供了一个validate函数作为整体表单校验，但是返回的是一个promise
      const valid = await formTarget.value.validate()
      if (valid) {
        // 发送请求
        // 用户账户登录方式
        // 登录成功之后跳转至首页或者来源页
        // 登录失败即显示登录失败提示
        try {
          const { account, password, mobile, code } = form
          await userAccountRegist({ account, password, mobile, code })
          // 进行跳转
          router.push(route.query.redirectUrl || '/login')
          // 成功消息提示
          Message({ type: 'success', text: '注册成功' })
        } catch (e) {
          // 失败提示
          if (e.response.data) {
            Message({ type: 'error', text: e.response.data.message || '注册失败' })
          }
        }
      }
    }
    // 倒计时的pasue 暂停 resume 开始
    // useIntervalFn (回调函数，执行间隔，是否立即开启)
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, false)
    onUnmounted(() => {
      pause()
    })

    // 发送验证码
    // 绑定发送验证码按钮的点击事件
    // 检验手机号，如果成功就发送，并开启60s倒计时， 不能再次点击，倒计时结束后恢复
    // 如果失败，就显示校验样式
    const send = async () => {
      const valid = mySchema.mobile(form.mobile)
      try {
        if (valid === true) {
        // 校验通过
        // 没有倒计时才发送
          if (time.value === 0) {
            await getRegMobileCode(form.mobile)
            Message({ type: 'success', text: '发送成功' })
            time.value = 60
            resume()
          }
        } else {
          // 失败 使用vee的错误函数显示错误信息，setFieldError(字段，错误信息)
          formTarget.value.setFieldError('mobile', valid)
        }
      } catch (e) {
        if (e.response) {
          Message({ type: 'error', text: '此号码' + e.response.data.message + '，请更换一个号码' || '失败' })
        }
      }
    }
    return { form, schema: mySchema, formTarget, time, send, submit }
  }
}
</script>

<style lang="less" scoped>
// 账号容器
.account-box {
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
